package com.yoomiito.app.broadcastreceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.yoomiito.app.base.App
import com.yoomiito.app.utils.AllCode
import com.yoomiito.app.utils.EventMessage
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.NetworkUtils
import org.greenrobot.eventbus.EventBus

/**
 * 网络状态监听
 */
class NetStateReceiver : BroadcastReceiver(){
    companion object{
        private const val NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"
        private val mInstance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            NetStateReceiver()
        }
        fun registerReceiver(){
            val intentFilter = IntentFilter()
            intentFilter.addAction(NET_CHANGE_ACTION)
            App.getInstance().registerReceiver(mInstance,intentFilter)
        }
    }
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action==NET_CHANGE_ACTION){
            L.i("收到网络变化")
            val b = NetworkUtils.checkNetPermission(App.getInstance())
            val eventMessage = EventMessage()
            eventMessage.eventType = if (b) AllCode.NET_DIALOG_SHOW else AllCode.NET_DIALOG_DISMISS
            EventBus.getDefault().post(eventMessage)
            L.i("已发送网络变化消息")
        }
    }
}